package com.user.Scheduler.OrderScheduler;

import com.user.dao.order.SchedOrder;
import com.user.mapper.OrderMapper;
import com.user.service.OrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
public class OrderCancellationScheduler {

    @Resource
    OrderMapper orderMapper;
    @Resource
    OrderService orderService;

    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void cancelUnpaidOrders() throws IOException {
        List<SchedOrder> unpaidOrders = orderMapper.selectUnpaidOrders();
        LocalDateTime now = LocalDateTime.now();
        for (SchedOrder order : unpaidOrders) {
            LocalDateTime orderTime = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            long minutesBetween = ChronoUnit.MINUTES.between(orderTime, now);
            if (minutesBetween >= 30) orderService.cancelOrder(order.getId());
        }
    }
}